// pages/maintenance/maintenance.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    pageHide: false,
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    modalName: null,
    providerList:[],
    providerId:'',
    tapLabelList:[],
    reportType:'',
    reportTypeList:{},
    // 当前选中的数据信息
    hoverReportType:{},
    drivingLicenseUrl:'', //行驶证上传图片 ---- 
    ocrDiscernData:{  //识别之后的数据
      vin:'',
      standardname2:'',
      importFlag:'',
      licensingTime:'',
      engineNo:'',
      plateNo:''
    },
    ChooseCar:null, //从车库里选择的车辆
    userAgreement: true, //同意用户协议
    dealerInfo:{},

    searchParams:{
      pageNum: 1,
      pageSize: 6,
      keyword:'',
      pages:'',
      total:'',
    },
    noData: true,
    orderList:{},
    onReachBottomLoading: false,
    orderStatus:{
      0:'待支付',
      1:'已支付(待查询)',
      2:'查询中',
      3:'报告已生成',
      4:'退款中',
      5:'已退款',
      6:'退款成功',
      99:'超时关闭',
      98:'已取消',
      97:'购买报告错误',
      96:'查询报告错误'
    },
    reporType:{
      'c300InsuranceReport':'车300碰撞保险记录',
      'c300MtnceReport':'车300保养维修记录',
      'cbsInsuranceReport':'查博士碰撞保险记录',
      'cbsMtnceReport':'查博士保养维修记录'
    },
    orderInfo:{
      orderNo:'',
      orderStatus: 0,
      payInfo:{}
    },
    // 报告样例。
    sampleReport:{
      'c300InsuranceReport':'https://customer.che300.com/ins-report-v2?cid=1513&order_id=12466140&sn=d1a315d8057d5dfe1eee0df9e5b81df6&version=2.0',
      'c300MtnceReport':'https://customer.che300.com/mtnce-report-v2-3?cid=1513&order_id=FC19813301543298&sn=6c004004d3c9d5ac27054fec4033b056&version=2.5#/FC19813301543298',
      'cbsInsuranceReport':'https://api.chaboshi.cn/new_report/show_reportMobile?userid=10728817&orderid=eed60d23238947f8a9c19fdb64a4d70b&timestamp=1639415625659&nonce=a9f0f5d1-664c-47a3-ab9f-8055eae69c46&signature=Oa4Ex4F%2BS3ZZgMwXalK1Oti%2B79E%3D',
      'cbsMtnceReport':'https://api.chaboshi.cn/new_report/show_reportMobile?userid=10728817&orderid=673c21be6a1d45dc8bdcbecf9a1f1256&timestamp=1639415694194&nonce=a871352c-9d0f-4069-9b8f-49dad9b9c927&signature=59Y3hHazz79luV1mu8G2klooM3Y%3D'
    },
    openChooseImage:false,
    seeImages: false
  },
  /**
   * 生命周期函数--监听页面加载
   */
  ocrDiscernDataVinChange(e){
    this.setData({
      'ocrDiscernData.vin': e.detail.value
    })
  },
  closeChangeVinText(){
    this.setData({
      'seeImages': false
    })
  },
  openChangeVinText(){
    this.cropper = this.selectComponent("#image-cropper");
    if(this.data.drivingLicenseUrl){
      this.cropper.pushImg(this.data.drivingLicenseUrl);
      this.cropper.imgReset();
    }
    this.setData({
      'seeImages': true
    })
  },
  doNothing(){},
  onShow: function (options) {
      console.log('触发Onshow',this.data.openChooseImage);
      if(!this.data.openChooseImage){
        this.InitUserStatus(options);
      }else{
        this.setData({
          'openChooseImage': false
        })
      }
  },
  // 检查一下登录状态。
  async InitUserStatus(options){
      app.showLoading("获取用户信息");
      await app.checkToken();
      this.InitUserInfo(options);
      wx.hideLoading();
  },
  InitUserInfo(options){
      let userInfo = app.globalData.userInfo;
      // 看是否需要回填参数。
      if(app.globalData.scopeRowCar){
        let scopeRowCar = app.deepCopy(app.globalData.scopeRowCar);
        app.globalData.scopeRowCar = null;
        if(this.data.drivingLicenseUrl == ''){
          this.inputChooseCarData(scopeRowCar);
        }else{
          if(this.data.ChooseCar){
            if(this.data.ChooseCar.vin == this.data.ocrDiscernData.vin){
              // 他们俩相等就说明是，之前选择的是车辆
              this.inputChooseCarData(scopeRowCar);
            }else{
              this.checkOrcAndChooseCar(scopeRowCar);
            }
          }else{
            this.checkOrcAndChooseCar(scopeRowCar);
          }
        }
      }
      this.loadDealerInfo();
      this.goQuery();
      this.reportConfigInfo();
      // 这里再验证一遍权限。
      // if (userInfo.roleList.indexOf('reportApplyAudit') == -1) {
      //     app.showNoAuthOrNoGrant('您无权操作查看此页面');
      //     return;
      // }else{
      // }
  },
  // 检查是否数据一致
  checkOrcAndChooseCar(scopeRowCar){
    if(this.data.ocrDiscernData.vin != scopeRowCar.vin){
      let self = this;
      wx.showModal({
        title: '选择提醒',
        content: '您当前所选择车辆与识别信息不一致，请选择依据哪一个选择进行查询操作',
        confirmText:'识别信息',
        cancelColor:'#576B95',
        cancelText:'所选车辆',
        success (res) {
          if (res.confirm) {
            // 依据识别信息
            self.setData({
              'ChooseCar': null
            })
          } else if (res.cancel) {
            // 依据所选车辆
            self.inputChooseCarData(scopeRowCar);
          }else{
            // 依旧依据识别信息
            self.setData({
              'ChooseCar': null
            })
          }
        }
      });
    }else{
      this.inputChooseCarData(scopeRowCar);
    }
  },
  // 填充选择车辆的参数。
  inputChooseCarData(scopeRowCar){
    // 回填参数
    console.log('scopeRowCar',scopeRowCar);
    this.setData({
      'ChooseCar' : scopeRowCar
    })
    let ocrDiscernData = {
      engineNo: scopeRowCar.engineNo || '',
      importFlag: scopeRowCar.importFlag || '',
      licensingTime: scopeRowCar.licensingTime || '',
      plateNo: scopeRowCar.plateNo || '',
      standardname2: scopeRowCar.shortVehicleName || '',
      vin: scopeRowCar.vin || ''
    };
    this.setData({
      'ocrDiscernData': ocrDiscernData
    });
    if(2 == scopeRowCar.ocrPicType){
      this.setData({
        'drivingLicenseUrl': scopeRowCar.ocrPicUrl
      })
    }else{
      this.setData({
        'drivingLicenseUrl': ''
      })
      app.alert('未识别到行驶证图片信息，请您上传');
    }
  },
  // 填充识别到的参数
  inputOcrDiscern(ocrResult){
    let ocrDiscernData = {
      engineNo: ocrResult.engineNo || '',
      importFlag: ocrResult.importFlag || '',
      licensingTime: ocrResult.licensingTime || '',
      plateNo: ocrResult.plateNo || '',
      standardname2: ocrResult.standardname2 || '',
      vin: ocrResult.vin || ''
    };
    this.setData({
      'ocrDiscernData':ocrDiscernData
    })
  },
  reportConfigInfo(){
    app.sHttp.reportConfigInfo().then(res =>{
      let reportTypeList = {};
      res.result.reportTypeList.forEach(item =>{
        reportTypeList[item.reportType] = item;
      });
      this.setData({
        'providerList': res.result.providerList,
        'reportTypeList': reportTypeList
      });
    },err=>{
      app.error(err.msg);
    })
  },
  clickProvider(e){
    let provider = this.data.providerList[e.currentTarget.dataset.idx];
    if(provider.status == 1){
      let tapLabelList = [];
      for (const key in this.data.reportTypeList) {
          if(key.indexOf(provider.providerId) != -1){
            tapLabelList.push(this.data.reportTypeList[key]);
          }
      }
      this.setData({
        'providerId': provider.providerId,
        'tapLabelList': tapLabelList,
        'reportType':''
      })
    }else{
      app.alert("当前数据源已停用");
    }
  },
  clickReportType(e){
    let tapLabel = this.data.tapLabelList[e.currentTarget.dataset.idx];
    if(tapLabel.status == 1){
      this.setData({
        'reportType': tapLabel.reportType
      })
    }else{
      app.alert("当前报告类型已停用");
    }
  },
  useUserAgreement(){
    this.setData({
      userAgreement: !this.data.userAgreement
    })
  },
  hideModal(e) {
      this.setData({
          modalName: null,
      })
  },
  showModal(e){
    this.setData({
      modalName: e.currentTarget.dataset.target
    })
  },
  // 上传图片方法-------------------------------------------------------
  chooseMessageFile(){
    this.hideModal();
    this.setData({
      'openChooseImage': true
    })
    wx.chooseMessageFile({
      count: 1,
      type: 'image',
      success: (res) => {
        console.log('微信回调',res);
        if(res.tempFiles){
          this.uploadTheImage(res.tempFiles[0].path);
        }
      }
    });
  },
  ChooseImageByxiangji() {
    this.hideModal();
    this.setData({
      'openChooseImage': true
    })
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['camera'],
      success: (res) => {
        console.log('微信回调',res);
        if(res.tempFilePaths){
          this.uploadTheImage(res.tempFilePaths[0]);
        }
      }
    });
  },
  ChooseImageByxiangce() {
    this.hideModal();
    this.setData({
      'openChooseImage': true
    })
    wx.chooseImage({
      count: 1, //默认1
      sizeType: ['compressed'], 
      sourceType: ['album'],
      success: (res) => {
        console.log('微信回调',res);
        if(res.tempFilePaths){
          this.uploadTheImage(res.tempFilePaths[0]);
        }
      }
    });
  },
  showUploadImage(){
    if(this.data.reportType == ''){
      this.setData({
        'modalName': 'reportTypeChoose'
      })
    }else{
      this.setData({
        'modalName': 'typeChoose'
      })
    }
  },
  // 上传图片
  async uploadTheImage(filePath){
    if(filePath.substring(filePath.length-3) == 'jpg'){
      const compressImage = app.promisify(wx.compressImage);
      console.log(filePath);
      const res = await compressImage({
        src: filePath, // 图片路径
        quality: 67 // 压缩质量
      });
      filePath = res.tempFilePath;
    } 
    let self = this;
    app.sHttp.upload({'filePath':filePath,'fileType':'report','isNeedThumbnail':0}).then(res=>{
      // 进行识别。
      self.ocrDiscern(res.originalUrl);
    },err=>{
      app.error(err.msg);
    })
  },
  // OCR识别数据
  ocrDiscern(drivingLicenseUrl){
    if ('' == drivingLicenseUrl) {
        app.alert('请上传需识别的图片');
        return;
    };
    // 进行识别操作.
    app.sHttp.ocrDiscern({cardType:2,imageUrl:drivingLicenseUrl}).then(res =>{
      let ocrResult = res.result;
      if(this.data.ChooseCar != null){
        if(ocrResult.vin != this.data.ChooseCar.vin){
          let self = this;
          wx.showModal({
            title: '选择提醒',
            content: '您当前识别信息与所选择车辆不一致，请选择依据哪一个选择进行查询操作',
            confirmText:'识别信息',
            cancelColor:'#576B95',
            cancelText:'所选车辆',
            success (res) {
              if (res.confirm) {
                // 依据识别信息
                self.inputOcrDiscern(ocrResult);
                self.setData({
                  'drivingLicenseUrl': drivingLicenseUrl,
                  'ChooseCar':null
                })
              } else {
                let ChooseCar = self.data.ChooseCar;
                if(2 == ChooseCar.ocrPicType){
                  self.setData({
                    'drivingLicenseUrl': ChooseCar.ocrPicUrl
                  })
                }else{
                  self.setData({
                    'drivingLicenseUrl': ''
                  })
                }
              }
            }
          })
        }else{
          this.inputOcrDiscern(ocrResult);
          this.setData({
            drivingLicenseUrl: drivingLicenseUrl
          });
        }
      }else{
        this.inputOcrDiscern(ocrResult);
        this.setData({
          drivingLicenseUrl: drivingLicenseUrl
        });
      }
    },err=>{
        app.error(err.msg);
    })
  },
  // 选择已上架车辆
  chooseGarageCar(){
    wx.navigateTo({
      url: '/pages/publicPage/chooseGarageCar/chooseGarageCar',
    })
  },
  // 跳转到列表
  carQueryRecord(){
    wx.redirectTo({
      url: '/pages/carQueryRecord/carQueryRecord'
    })
  },

  // 立即去查询！
  goReportOrder(){
    // 校验参数。1.是否存在行驶证图片信息。
    // 2.是否存在VIN码
    // 3.是否选择数据源
    this.hideModal();
    if(this.data.drivingLicenseUrl == ''){
      this.showUploadImage();
      return;
    }
    if(this.data.ocrDiscernData.vin == ''){
      app.alert('请上传行驶证，或选择上架车辆进行查询');
      return;
    }
    if(this.data.reportType == ''){
      this.setData({
        'modalName':'noReportType'
      })
      return;
    }
    if(!this.data.userAgreement){
      let self = this;
      wx.showModal({
        title: '温馨提示',
        content: '使用本服务表明您已同意《用户协议》',
        confirmText:'同意协议',
        cancelColor:'#576B95',
        cancelText:'暂不查询',
        success (res) {
          if (res.confirm) {
            self.setData({
              'userAgreement':true
            });
            self.goReportOrder();
          }
        }
      });
    }else{
      // 组装一个需要带到下个提交订单页面的数据。
      let subReportOrderData = {
        vin: this.data.ocrDiscernData.vin,
        engineNo: this.data.ocrDiscernData.engineNo,
        plateNo: this.data.ocrDiscernData.plateNo,
        drivingLicenseUrl: this.data.drivingLicenseUrl,
        reportType: this.data.reportType,
        standardname2: this.data.ocrDiscernData.standardname2
      };
      app.globalData.subReportOrderData = subReportOrderData;
      console.log(app.globalData.subReportOrderData);
      wx.navigateTo({
        url: '/pages/maintenance/subOrder/subOrder',
      })
    }
  },
  // 查询车辆列表。
  goQuery(){
    console.log('触发查询');
    this.setData({
      'searchParams.pageNum':1,
      'searchParams.total':'',
      'searchParams.pages':'',
      'orderList': {}
    });
    this.reportOrderList(this.data.searchParams);
  },
  reportOrderList(searchParams){
    this.setData({
        'onReachBottomLoading': true
    })
    app.sHttp.reportOrderList(searchParams).then(res=>{
      let orderList = this.data.orderList;
      orderList[searchParams.pageNum] = res.result.reportOrderList;
      if (0 == res.result.total) {
        this.setData({
          'noData': true,
          'onReachBottomLoading': false
        })
      }else{
        this.setData({
          'noData': false,
          'orderList': orderList,
          'searchParams.total':res.result.total,
          'searchParams.pages': res.result.pages,
          'onReachBottomLoading': false
        });
      }
    },err=>{
      app.error(err.msg);
      this.setData({
        'onReachBottomLoading': false
      })
    })
  },
  onHide(){
    this.setData({
      'pageHide': true
    })
  },
  onReachBottom(){
    if(this.data.pageHide){
      this.setData({
        'pageHide': false
      });
      return;
    }
    if (this.data.searchParams.pageNum == this.data.searchParams.pages) {
        //app.alert('没有更多了哦~');
    }else{
        let self = this;
        this.setData({
            'searchParams.pageNum': self.data.searchParams.pageNum+1
        });
        this.reportOrderList(this.data.searchParams);
    }
  },
  copyText: function (e) {
    wx.setClipboardData({
      data: e.currentTarget.dataset.text,
      success: function (res) {
        wx.getClipboardData({
          success: function (res) {
            wx.showToast({
              title: '复制成功'
            })
          }
        })
      }
    })
  },
  lookReprotInfo(e){
    this.hideModal();
    app.globalData.lookReportInfoUrl = e.currentTarget.dataset.url;
    wx.navigateTo({
      url: '/pages/carQueryRecord/detailed/detailed',
    })
  },
  // 拉起重新支付。
  reportOrderPayInfo(e){
    let self = this;
    let orderNo = e.currentTarget.dataset.orderno;
    app.sHttp.reportOrderPayInfo(orderNo).then(res=>{
      this.setData({
        'orderInfo.payInfo': res.payInfo,
        'orderInfo.orderNo': orderNo,
      }, () => {
        self.tuneUpPay();
      });
    },err=>{
      app.error(err.msg);
    })
  },
  reportOrderCancel(e){
    let self = this;
    wx.showModal({
      title: '提示',
      content: '您确定要取消当前订单',
      success (res) {
        if (res.confirm) {
          let orderNo = e.currentTarget.dataset.orderno;
          app.sHttp.reportOrderCancel(orderNo).then(res=>{
            app.alert('取消成功,已退还余额与积分');
            let that = self;
            setTimeout(() => {
              that.goQuery();
            }, 1500);
          },err=>{
            app.error(err.msg);
          })

        }
      }
    })
  },
  tuneUpPay(){
    // 从Data里面拿参数
    let orderInfo = this.data.orderInfo;
    try {
      if ('' == orderInfo.orderNo || undefined == orderInfo.payInfo.paySign) {
        app.alert('支付参数不完整');
        return;
      };
      // 吊起支付。
      let self = this;
      wx.requestPayment({
          timeStamp: orderInfo.payInfo.timeStamp,
          nonceStr: orderInfo.payInfo.nonceStr,
          package: orderInfo.payInfo.package,
          signType: orderInfo.payInfo.signType,
          paySign: orderInfo.payInfo.paySign,
          success (res) {
              // 查询订单完成信息。
              let _this = self;
              app.showLoading('查询订单状态');
              setTimeout(() => {
                  wx.hideLoading();
                  _this.OrderPayResult();
              }, 5000);
          },
          fail (res) {
            self.payOk('支付失败','您已取消支付，可在订单列表中选择继续支付');
          }
      })
    } catch (error) {
      app.alert('支付参数不完整');
    }
  },
  OrderPayResult(){
      let orderInfo = this.data.orderInfo;
      if ('' == orderInfo.orderNo) {
          app.alert('支付参数不完整');
          return;
      };
      app.sHttp.reportOrderPayResult(orderInfo.orderNo).then(res =>{
          let orderStatus = res.orderStatus;
          if (0 == orderStatus) {
              this.payOk('查询结果','请等待几分钟后在订单列表中查看订单状态，如长时间未显示成功状态，请联系客服处理');
              return;
          }else if (1 == orderStatus) {
              this.payOk('提交完成','您当前订单提交完成，请等待报告结果');
              return;
          }else{
            this.payOk('查询结果','请等待几分钟后刷新查看，如长时间未显示成功状态，请联系客服处理');
          }
      },err=>{
        app.error(err.msg);
      })
  },
  payOk(title,content){
    let self = this;
    wx.showModal({
      title: title,
      content: content,
      confirmText: '我知道了',
      showCancel: false,
      success(res) {
          self.goQuery();
      }
    })
  },
  // 加载下车商的信息。
  loadDealerInfo(){
    if(Object.keys(app.globalData.dealerInfo).length === 0){
      app.sHttp.dealerInfo().then(res =>{
        // 判断认证时间。
        if(undefined == res.result.authExpiryTime || null == res.result.authExpiryTime || '' == res.result.authExpiryTime){
            res.result.authExpiryStatus = 0;
        }else{
            let howMinute = (((Date.parse(new Date())) - res.result.authExpiryTime) / 1000) / 60;
            if(howMinute>=0){
                res.result.authExpiryStatus = 0;
            }else{
                res.result.authExpiryStatus = 1;
            }
        }
        if(undefined == res.result.goldMedalExpiryTime || null == res.result.goldMedalExpiryTime || '' == res.result.goldMedalExpiryTime){
            res.result.goldMedalExpiryStatus = 0;
        }else{
            let howMinute = (((Date.parse(new Date())) - res.result.goldMedalExpiryTime) / 1000) / 60;
            if(howMinute>=0){
                res.result.goldMedalExpiryStatus = 0;
            }else{
                res.result.goldMedalExpiryStatus = 1;
            }
        }
        app.globalData.dealerInfo = res.result;
        let dealerInfo = res.result;
        // 验证优先享受了哪个价格
        if(1 == dealerInfo.isTransactionGuarantee){
          dealerInfo['enjoyThePrice'] = "isTransactionGuarantee";
        }else if(1 == dealerInfo.goldMedalExpiryStatus){
          dealerInfo['enjoyThePrice'] = "goldMedalExpiryStatus";
        }else if(1 == dealerInfo.authExpiryStatus){
          dealerInfo['enjoyThePrice'] = "authExpiryStatus";
        }else{
          dealerInfo['enjoyThePrice'] = "";
        }
        this.setData({
          'dealerInfo': dealerInfo
        })
      },err=>{
      })
    }else{
      let dealerInfo = app.globalData.dealerInfo;
      // 验证优先享受了哪个价格
      if(1 == dealerInfo.isTransactionGuarantee){
        dealerInfo['enjoyThePrice'] = "isTransactionGuarantee";
      }else if(1 == dealerInfo.goldMedalExpiryStatus){
        dealerInfo['enjoyThePrice'] = "goldMedalExpiryStatus";
      }else if(1 == dealerInfo.authExpiryStatus){
        dealerInfo['enjoyThePrice'] = "authExpiryStatus";
      }else{
        dealerInfo['enjoyThePrice'] = "";
      }
      this.setData({
        'dealerInfo': dealerInfo
      })
    };
  },
  jumpToWallet(){
    wx.navigateTo({
      url: '/pages/me/wallet/wallet?show=recharge',
    })
  },
  jumpToManageDealer(e){
    wx.navigateTo({
      url: '/pages/me/manageDealer/manageDealer?type='+e.currentTarget.dataset.type,
    })
  },
  jumpToUserAgreement(){
    this.hideModal();
    wx.navigateTo({
      url: '/pages/publicPage/userAgreement/userAgreement',
    })
  },
  seeSampleReportShowModal(){
    try {
      if(this.data.reportType == ''){
        if(this.data.modalName == null){
          let self = this;
          wx.showModal({
            title: '提示',
            content: '请先选择您想要查看的报告类型',
            confirmText:'去选择',
            success (res) {
              if (res.confirm) {
                self.setData({
                  'modalName': 'wantSeeReportYL'
                })
              }
            }
          })
        }else{
          app.alert('请选择数据源');
        }
        return;
      }
      let url = this.data.sampleReport[this.data.reportType];
      app.globalData.lookReportInfoUrl = url;
      this.hideModal();
      wx.navigateTo({
        url: '/pages/carQueryRecord/detailed/detailed',
      })
    } catch (error) {
      app.alert('未找到相关样例');
    }
  },
  openCustomerServiceChat(){
    app.openCustomerServiceChat();
  },
  JumpToRecordOrderDetails(e){
    try {
      let page = e.currentTarget.dataset.page;
      let index = e.currentTarget.dataset.idx;
      let item = this.data.orderList[page][index];
      app.globalData.scopeRowReport = item;
      wx.navigateTo({
        url: '/pages/carQueryRecord/details/details',
      })
    } catch (error) {
      app.alert('缺少必要数据，请关闭重试');
    }
  },
})